package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.utils.SortUtil;
import com.qinglei.recoup.system.dao.BedHealthBreathDailyDataMapper;
import com.qinglei.recoup.system.dao.BedMapper;
import com.qinglei.recoup.system.dao.RadarMapper;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.dao.RadarWechatMapper;
import com.qinglei.recoup.system.pojo.RadarWechatParam;
import com.qinglei.recoup.system.service.RadarWechatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglei.recoup.system.service.UserWechatService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dqh
 */
@Service
public class RadarWechatServiceImpl extends ServiceImpl<RadarWechatMapper, RadarWechat> implements RadarWechatService {

    @Autowired
    private RadarMapper radarMapper;

    @Autowired
    private RadarWechatMapper  radarWechatMapper;

    @Autowired
    private UserWechatService userWechatService;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private  BedHealthBreathDailyDataMapper  bedHealthBreathDailyDataMapper;
    @Override
    public CommonRes add(RadarWechat radarWechat) {
        String sn_code = radarWechat.getSnCode();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("sn_code",sn_code);
        wrapper.eq("is_deleted",0);
        wrapper.eq("type",1);
        Radar Radar = radarMapper.selectOne(wrapper);
        if(Radar==null){
            return CommonRes.failed().setMsg("绑定失败，请输入正确的设备码");
        }

        Bed bed = bedMapper.selectBySn(sn_code);
        if(bed==null){
            return CommonRes.failed().setMsg("该设备未绑定床位");
        }
        String openId = radarWechat.getOpenId();
        if(StringUtils.isEmpty(openId)){
            return CommonRes.failed().setMsg("!");
        }
        UserWechat userWechat  = userWechatService.getOne(new QueryWrapper<UserWechat>().eq("open_id",openId));
        if(userWechat == null){
            return CommonRes.failed().setMsg("未找到该openId下绑定的用户!");
        }

        RadarWechat radarWechatTmp = radarWechatMapper.selectOne(new QueryWrapper<RadarWechat>().eq("user_wechat_id",userWechat.getId())
                .eq("sn_code",sn_code).eq("is_deleted",0));

        if(radarWechatTmp!=null){
            return CommonRes.failed().setMsg("设备码为："+sn_code+"的设备已经绑定!");
        }

        radarWechat.setUserWechatId(new Long(userWechat.getId()));
        radarWechatMapper.insert(radarWechat);
        return CommonRes.ok().setMsg("绑定成功！");
    }

    @Override
    public CommonRes remove(Long radarWechatId,String snCode) {
        if(radarWechatId==null){
            return CommonRes.failed().setMsg("radarWechatId不能为空！");
        }

        if(snCode==null){
            return CommonRes.failed().setMsg("设备码不能为空");
        }


        QueryWrapper<RadarWechat> queryWrapperTmp = new QueryWrapper<>();
        queryWrapperTmp.eq("id",radarWechatId);
        queryWrapperTmp.eq("is_deleted",0);
        queryWrapperTmp.eq("sn_code",snCode);

        RadarWechat radarWechatTmp = radarWechatMapper.selectOne(queryWrapperTmp);
        if(radarWechatTmp==null){
            return CommonRes.failed().setMsg("该设备未绑定！");
        }

        UpdateWrapper<RadarWechat> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",radarWechatId).set("is_deleted",1);
        if( radarWechatMapper.update(null,updateWrapper)==1){
            return  CommonRes.ok().setMsg("解绑成功！");
        }
        return CommonRes.failed();
    }

    @Override
    public CommonRes listForOpenId(RadarWechatParam  radarWechatParam) {
        String openId = radarWechatParam.getOpenId();
        if(StringUtils.isEmpty(openId)){
            return CommonRes.failed().setMsg("暂未登录");
        }
        UserWechat userWechat = userWechatService.getOne(new QueryWrapper<UserWechat>().eq("open_id",openId).eq("is_deleted",0));
        if(userWechat==null){
            return CommonRes.failed().setMsg("该微信号未注册！");
        }
        Page<RadarWechat> page = new Page<>();
        SortUtil.handlePageSort(radarWechatParam, page);
        IPage<RadarWechat>  radarWechat= radarWechatMapper.findList(page,userWechat.getId());
        radarWechat.getRecords().forEach(item->{
            if(!StringUtils.isEmpty(item.getSnCode())){
                Bed bed = bedMapper.selectBySn(item.getSnCode());
                if(bed!=null){
                    item.setBedId(bed.getId());
                }
            }


        });
        return CommonRes.ok(radarWechat);
    }

    @Override
    public CommonRes subscribe(String openId, String snCode, Integer isSubscribe) {
        if(StringUtils.isEmpty(openId)){
            return CommonRes.failed().setMsg("暂未登录");
        }

        if(StringUtils.isEmpty(snCode)){
            return CommonRes.failed().setMsg("设备码不能为空");
        }
        if(isSubscribe==null){
            return CommonRes.failed().setMsg("isSubscribe不能为空！");
        }


        QueryWrapper<UserWechat> queryWrapperTmp = new QueryWrapper<>();
        queryWrapperTmp.eq("open_id",openId);
        queryWrapperTmp.eq("is_deleted",0);
        UserWechat userWechat = userWechatService.getOne(queryWrapperTmp);
        if(userWechat==null){
            return CommonRes.failed().setMsg("当前微信号未注册！");
        }

        QueryWrapper<RadarWechat> queryRadarWechatTmp = new QueryWrapper<>();
        queryRadarWechatTmp.eq("user_wechat_id",userWechat.getId());
        queryRadarWechatTmp.eq("sn_code",snCode);
        queryRadarWechatTmp.eq("is_deleted",0);

        RadarWechat radarWechatTmp = radarWechatMapper.selectOne(queryRadarWechatTmp);
        if(radarWechatTmp==null){
            return CommonRes.failed().setMsg("该设备未绑定！");
        }

        if(isSubscribe == radarWechatTmp.getIsSubscribe()){
            if(isSubscribe==0){
                return CommonRes.failed().setMsg("该设备未订阅！");
            }else{
                return CommonRes.failed().setMsg("该设备已订阅！");
            }

        }
        UpdateWrapper<RadarWechat> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",radarWechatTmp.getId()).set("is_subscribe",isSubscribe);
        if( radarWechatMapper.update(null,updateWrapper)==1){
            return  CommonRes.ok().setMsg("操作成功！");
        }
        return CommonRes.failed();
    }

    @Override
    public CommonRes addOrUpdatelabel(RadarWechat radarWechat) {
        if(StringUtils.isEmpty(radarWechat.getOpenId())){
            return CommonRes.failed().setMsg("暂未登录");
        }

        if(StringUtils.isEmpty(radarWechat.getSnCode())){
            return CommonRes.failed().setMsg("snCode号不能为空！");
        }

        if(StringUtils.isEmpty(radarWechat.getNickName())){
            return CommonRes.failed().setMsg("nickName号不能为空！");
        }

        QueryWrapper<UserWechat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",radarWechat.getOpenId()).eq("is_deleted",0);
        UserWechat  userWechat = userWechatService.getOne(queryWrapper);
        if(userWechat == null){
            return CommonRes.failed().setMsg("当前微信号未注册！");
        }
        radarWechat.setUserWechatId(new Long(userWechat.getId()));

        String sn_code = radarWechat.getSnCode();
        RadarWechat radarWechatTmp = radarWechatMapper.selectOne(new QueryWrapper<RadarWechat>().eq("user_wechat_id",userWechat.getId())
                .eq("sn_code",sn_code).eq("is_deleted",0));

        if(radarWechatTmp!=null){
            return CommonRes.failed().setMsg("设备码为："+sn_code+"的设备已经绑定!");
        }

        if( radarWechatMapper.insert(radarWechat)==1){
            return  CommonRes.ok().setMsg("操作成功！");
        }
        return CommonRes.failed();
    }

    @Override
    public CommonRes healthReportList(String snCode,String openId) {
        if(StringUtils.isEmpty(snCode)){
            return CommonRes.failed().setMsg("snCode号不能为空！");
        }
        if(StringUtils.isEmpty(openId)){
            return CommonRes.failed().setMsg("暂未登录");
        }

        Bed bed = bedMapper.selectBySn(snCode);
        if (bed == null) {
            return  CommonRes.failed().setMsg("该设备号下未绑定床位");
        }
        QueryWrapper<UserWechat> queryUserWechat = new QueryWrapper<>();
        queryUserWechat.eq("open_id",openId).eq("is_deleted",0);
        UserWechat userWechat = userWechatService.getOne(queryUserWechat);
        if (userWechat == null) {
            return  CommonRes.failed().setMsg("该微信号未注册！");
        }

        QueryWrapper<RadarWechat> queryRadarWechat = new QueryWrapper<>();
        queryRadarWechat.eq("sn_code",snCode).eq("user_wechat_id",userWechat.getId()).eq("is_deleted",0);
        RadarWechat radarWechat = radarWechatMapper.selectOne(queryRadarWechat);
        if (radarWechat == null) {
            return  CommonRes.failed().setMsg("该微信号未绑定sn号为："+snCode+" 的设备");
        }

        List <Map<String,Object>>  healthReportListOneWeek  =bedHealthBreathDailyDataMapper.getHealthReportListOneWeek(bed.getId());
        Map<String,Object>   resultList = new HashMap<>();
        healthReportListOneWeek.forEach(itemMap->{
            System.out.println(itemMap);
            itemMap.put("bedName",bed.getName());
            itemMap.put("nickName",radarWechat.getNickName());
        });

        resultList.put("healthReportListOneWeek",healthReportListOneWeek);

        if(healthReportListOneWeek!=null && healthReportListOneWeek.size()>0){
            LocalDate now = LocalDate.now();
            LocalDate localDate = LocalDate.of(now.getYear(), now.getMonth(), now.getDayOfMonth()-1);
            LocalDate weekOfDay = localDate.plusDays(-6);
            LocalDate monthOfDay = localDate.plusDays(-29);
            System.out.println(weekOfDay);

            Map<String,Object> weekData = new HashMap<>();
            Map<String,Object> monthData = new HashMap<>();
            //weekData.put("sn",snCode);
            weekData.put("startTime",weekOfDay);
            weekData.put("endTime",localDate);
            weekData.put("bedId",bed.getId());
            weekData.put("bedName",bed.getName());
            weekData.put("nickName",radarWechat.getNickName());
            //monthData.put("sn",snCode);
            monthData.put("startTime",monthOfDay);
            monthData.put("endTime",localDate);
            monthData.put("bedId",bed.getId());
            monthData.put("bedName",bed.getName());
            monthData.put("nickName",radarWechat.getNickName());
            resultList.put("weekData",weekData);
            resultList.put("monthData",monthData);
        }

        return CommonRes.ok(resultList).setMsg("成功！");
    }

    @Override
    public CommonRes IsBindingOpenId(String snCode, String openId) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("sn_code",snCode);
        wrapper.eq("is_deleted",0);
        wrapper.eq("type",1);
        Radar Radar = radarMapper.selectOne(wrapper);
        if(Radar==null){
            return CommonRes.failed(false).setMsg("绑定失败，请输入正确的设备码");
        }

        Bed bed = bedMapper.selectBySn(snCode);
        if(bed==null){
            return CommonRes.failed().setMsg("该设备未绑定床位");
        }

        if(StringUtils.isEmpty(openId)){
            return CommonRes.failed(false).setMsg("!");
        }
        UserWechat userWechat  = userWechatService.getOne(new QueryWrapper<UserWechat>().eq("open_id",openId));
        if(userWechat == null){
            return CommonRes.failed(false).setMsg("未找到该openId下绑定的用户!");
        }

        RadarWechat radarWechatTmp = radarWechatMapper.selectOne(new QueryWrapper<RadarWechat>().eq("user_wechat_id",userWechat.getId())
                .eq("sn_code",snCode).eq("is_deleted",0));

        if(radarWechatTmp!=null){
            return CommonRes.failed(false).setMsg("设备码为："+snCode+"的设备已经绑定!");
        }
        return CommonRes.ok(true);
    }


    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        LocalDate localDate = LocalDate.of(now.getYear(), now.getMonth(), now.getDayOfMonth()-1);
        System.out.println(localDate);
        LocalDate weekOfDay = localDate.plusDays(-7);
        System.out.println(weekOfDay);
        LocalDate monthOfDay = localDate.plusDays(-30);
        System.out.println(monthOfDay);
    }

}
